<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    /* 
      思路：https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/solution/js-er-fen-fa-by-hblvsjtu/
      目标：查找到mid = target时的下标。target > nums[mid]时，从mid右边找target，否则从mid左边开始找。
        查找到mid后，以mid下标为基准，设两个指针，分别向两边移动，直到下个值不等于未开始移动时的值。
     */
    let nums = [5,7,7,8,8,10], target = 8;
    // let nums = [5,7,7,8,8,10], target = 6;

    function searchRange(nums, target) {
      let start = 0, end = nums.length - 1, mid;

      while (start <= end) {
        mid = start + end >> 1;
        if (nums[mid] === target) break;

        if (target > nums[mid])
          start = mid + 1;
        else 
          end = mid - 1;
      }
      if (start > end) return [-1, -1];

      let i = mid, j = mid;
      while (nums[i] === nums[i-1]) i--;
      while (nums[j] === nums[j+1]) j++;
      return [i, j];
    }

    /* 
      2.巧用内置函数解决：
     */
    // function searchRange(nums, target) {
    //   return [nums.indexOf(target), nums.lastIndexOf(target)]
    // }
    console.log(searchRange(nums, target));
  </script>
</body>
</html>